//
//  ProductsListCell.swift
//  iWatchManager
//
//  Created by GujyHy on 2018/1/23.
//  Copyright © 2018年 GujyHy. All rights reserved.
//

import UIKit
import SnapKit


protocol ProductsListCellDelegate {

    func productListCellAlbumBtnClicked(_ cell:ProductsListCell)
    // delete image
    func productListCellDeleteItemImage(_ cell:ProductsListCell, withIndex index:Int)
    // preview photos
    func productListCellPreviewPhotos(_ cell:ProductsListCell, withIndex index:Int)
    
}

class ProductsListCell: UITableViewCell {
    
    var delegate:ProductsListCellDelegate?
    
    
    var selectedPhotos:[UIImage] = [UIImage]()
    var selectedAssets:[Any]     = [Any]()
 
    // MARK: - life cycle
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.contentView.addSubview(self.typeNameLabel)
        self.contentView.addSubview(self.collectionView)
        
        self.layer.addSublayer(self.linelayer)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reloadData(){
        self.collectionView.reloadData()
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.typeNameLabel.frame = CGRect(x: AdaptedWidthValue(x: 15),y:0,
                                          width: self.frame.size.width,
                                          height: 35)
        
        self.collectionView.frame = CGRect(x: 0, y: 35,
                                           width: self.frame.size.width,
                                           height: self.frame.size.height - 35)
        let itemWH = Constant.getItemWidth(boundWidth: self.collectionView.frame.size.width)
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        layout.minimumLineSpacing = Constant.minLineSpacing
        layout.minimumInteritemSpacing = Constant.minItemSpacing
        self.collectionView.collectionViewLayout = self.layout
        
        self.linelayer.frame     = CGRect(x: 0, y: self.frame.size.height - 0.5,
                                          width: self.frame.size.width,
                                          height: 0.5)
    }
    
    // 类型
    open lazy var typeNameLabel:UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.clear
        label.textColor = UIColor.black
        label.font = kSystemFontWithSize(s: 16)
        label.textAlignment = NSTextAlignment.left
        return label
    }()
    
    // MARK: 懒加载
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        // LxGridViewFlowLayout 可拖动
        let layout = UICollectionViewFlowLayout()
        return layout
    }()
    open lazy var collectionView:UICollectionView = {
        let collectionview = UICollectionView(frame: self.bounds, collectionViewLayout: self.layout)
        collectionview.backgroundColor = .white
        collectionview.dataSource = self
        collectionview.delegate   = self
        collectionview.isScrollEnabled = false
        collectionview.contentInset = UIEdgeInsetsMake(Constant.offset,Constant.offset,Constant.offset, Constant.offset)
        collectionview.register(ProductImagesCell.self, forCellWithReuseIdentifier: "ProductImagesCell")
        return collectionview
    }()
    
    fileprivate var linelayer:CALayer = {
        let layer = CALayer()
        layer.backgroundColor = UIColor(hex:"e0e0e0").cgColor
        return layer
    }()
    
    // MARK: Private
    func albumAddBtnSelected() {
        if let nDelegate = self.delegate {
            nDelegate.productListCellAlbumBtnClicked(self)
        }
    }
    
    func previewPhotos(_ index:Int) {
        if let nDelegate = self.delegate {
            nDelegate.productListCellPreviewPhotos(self, withIndex: index)
        }
    }
    
    // MARK: Events
    @objc func deleteBtnClicked(_ button:UIButton) {
        let index = button.tag
        if let nDelegate = self.delegate {
            nDelegate.productListCellDeleteItemImage(self, withIndex: index)
        }
        
    }
 
}

extension ProductsListCell:UICollectionViewDataSource {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.selectedPhotos.count + 1
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:ProductImagesCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductImagesCell", for: indexPath) as! ProductImagesCell
        cell.backgroundColor = .white
        let row = indexPath.row
        if row == self.selectedPhotos.count {
            cell.imageView.image = UIImage(named:"AlbumAddBtn")
            cell.deleteBtn.isHidden = true
        }else{
            cell.imageView.image = self.selectedPhotos[row]
            cell.deleteBtn.isHidden = false
        }
        
        cell.deleteBtn.tag = row
        cell.deleteBtn.addTarget(self, action: #selector(deleteBtnClicked), for: .touchUpInside)
        
        return cell
    }
}

extension ProductsListCell:UICollectionViewDelegate {
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let row = indexPath.row
        if (row == self.selectedPhotos.count) {
            //            BOOL showSheet = self.showSheetSwitch.isOn;
            //            if (showSheet) {
            //                UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
            //                [sheet showInView:self.view];
            //            } else {
            self.albumAddBtnSelected()
            //            }
        }else{
            self.previewPhotos(row)
        }
    }
}





